const path = require('path');
const fs = require('fs');
const glob = require('glob');

const baseDir = process.cwd();
const SRC_DIR = path.join(baseDir + '/src/pages');

const oldWordStr = require('./wordString.js');
const enValue = require('./translatesTxt.js');
const WorkBook = require('./toExcell.js');
const reg = /i18next\.t\(\n*\s*["|']([\s\S]+?)["|']\n*\s*\)/g;

function getAllFiles() {
  return new Promise((resolve, reject) => {
    glob(
      `${SRC_DIR}/**/**.*(js|tsx)`, // 匹配后缀名为js或tsx的文件
      (err, files) => {
        if (err) reject(err);
        resolve(files);
      },
    );
  });
}

/** =================================收集文案====================================== */
async function getI18NextWord(fileList) {
  const tmpObj = {};
  if (fileList && fileList.length) {
    fileList.map((path) => {
      const str = fs.readFileSync(path, 'utf8');
      const res = str.match(reg);
      if (res && res.length) {
        res.map((str) => {
          const key = str.replace(reg, `$1`);
          tmpObj[key] = 1;
          return key;
        });
      }
    });
  }
  return tmpObj;
}

function getNewTemObj(tmpObj = {}) {
  // const restTmpObj = {};
  Object.keys(tmpObj).forEach((key) => {
    if (!oldWordStr[key]) {
      console.log('====== new word', key);
      // restTmpObj[key] = 1;
    }
  });
  if (enValue.length) {
    // 全量替换
    fs.writeFileSync(
      path.join(baseDir + '/locale/scripts/wordString.js'),
      'module.exports = ' + JSON.stringify(tmpObj),
    );
  }
  return tmpObj;
}

/** =================================写excel====================================== */
const writeExcel = (data, fileName, callback) => {
  const wordArrData = {
    Sheet1: data,
  };
  // 写入文件
  const wb = new WorkBook(wordArrData);
  wb.writeFile(fileName, callback);
};

const getNewWord = (tmpObj = {}) => {
  const wordArr = Object.keys(tmpObj).map((item) => [item]);
  if (!wordArr.length) return console.log('======== 没有新增多语言');
  writeExcel(
    wordArr,
    path.join(baseDir + `/locale/文案_${new Date().toDateString()}.xlsx`),
    console.log('======== 请到excel表中查看词条'),
  );
};

/** =================================生成json文件====================================== */
const writeJson = (tmpObj, enValue) => {
  if (!Object.keys(tmpObj).length) return;
  let str = '{';
  let langStr = '{';
  Object.keys(tmpObj).forEach((tmp, index) => {
    console.log('~~~~tmp~~~', tmp);
    str += `\n\t"web_lang_key_${index}": "${enValue[index]}",`;
    langStr += `\n\t"web_lang_key_${index}": "${tmp}",`;
  });
  str = str.slice(0, -1);
  str += '\n}';
  langStr = langStr.slice(0, -1);
  langStr += '\n}';
  // 生成英文词条
  fs.writeFileSync(path.join(baseDir + '/locale/lang/en-US.json'), str);
  // 生成key，用于i18包裹的中文文案和英文key相对应
  fs.writeFileSync(path.join(baseDir + '/locale/lang/langKey.json'), langStr);

  console.log('生成了语言json文件');
};

function getLangExcell(newTemObj) {
  writeJson(newTemObj, enValue);
  // 清除translatesTxt.js的内容
  fs.writeFileSync(
    path.join(baseDir + '/locale/scripts/translatesTxt.js'),
    'module.exports = []',
  );
}

/** =================================入口====================================== */
async function getAllWord() {
  const fileList = await getAllFiles();
  const temObj = await getI18NextWord(fileList);
  const newTemObj = getNewTemObj(temObj);
  if (enValue.length) {
    getLangExcell(newTemObj);
  } else {
    getNewWord(newTemObj);
  }
}
getAllWord();
